package com.gaoyi.crm.vm.base;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.gaoyi.crm.app.MyApplication;
import com.gaoyi.crm.callback.IView;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

public class BaseViewModel extends AndroidViewModel implements DefaultLifecycleObserver {

    protected final MyApplication mApplication;
    protected WeakReference<IView> mViewRef;

    public BaseViewModel(@NonNull Application application) {
        super(application);
        this.mApplication = (MyApplication) application;
    }

    public void attachView(IView view) {
        mViewRef = new WeakReference<>(view);
    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
        }
    }

    protected IView getView() {
        if (mViewRef != null) {
            return mViewRef.get();
        }
        return null;
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        if (EventBus.getDefault().isRegistered(owner.getLifecycle())) {
            EventBus.getDefault().unregister(owner.getLifecycle());
        }
        detachView();
    }
}
